import {
  getPassword,
  setPassword,
  getUserName,
  setUserName,
  getUserInfo,
  setUserInfo
} from "../../../utils/store"

// index.js
const app = getApp()
const {
  store
} = app;
Component({
  useStore: true,
  data: {
      intervalId:null,
    currentWeight:'',
    awbUrl: app.globalData.awbUrl,
    billVo:null,
    page: null,
      mock:{
          items:['平板纸','平板纸','平板纸','平板纸','平板纸','平板纸','平板纸','平板纸','平板纸','平板纸','平板纸'],
      },
      timer:null,// 验证码定时器
      countdown:60,
      phoneNumber:'',
      btnSendCaptchaText:'验证码',
      captcha:'',
      selfhandleDeviceList:null,
      poundbillList:null,
      showDialog:false,
      showBindPhoneDialog:false,
      showPoundBillDialog:false,
  },
    observers: {
 /*       'billVo.selfhandIp': function(selfhandip) {
            console.log('observers  billVo 变化')
            let that=this;
            if (this.data.intervalId){
                console.log('清除定时器'+this.data.intervalId)
                clearInterval(this.data.intervalId);
            }
           if (selfhandip!=''){
                // 每1000毫秒（1秒）执行一次 this.getCurrentWeightByIp 函数  开始循环查询磅的重量。
                this.data.intervalId = setInterval(function () {
                    that.getCurrentWeightByIp()
                }, 30*1000);
                that.setData({
                    currentWeight:'49.22'
                })

            }
        }*/
    },


    methods: {
        created: function() {
            console.log('created')
        },

        /**
         * 页面相关事件处理函数--监听用户下拉动作
         */
        onPullDownRefresh() {
            console.log('onPullDownRefresh')
            this.listSelfhandDevice();
            this.getInProcessBill();
            this.listFinishedBillByOpenId()
            wx.stopPullDownRefresh(); // 刷新完毕后停止下拉刷新动画
        },

        onUnload: function() {
            console.log('onUnload')
            // 页面销毁时执行
            clearInterval(this.data.intervalId);
            if (this.data.timer) {
                clearInterval(this.data.timer);
                this.data.timer = null;
                this.data.countdown=60
            }
        },
        detached: function() {
            console.log('detached')
            // 页面销毁时执行
            clearInterval(this.data.intervalId);
        },

        // 事件处理函数
        onLoad(query) {
            // 优先使用通过模板消息传递的openid
            let  openId=query.openId;
            if (openId&&openId!==''){
                wx.setStorageSync('awbopenid',openId)
            }else {
                if (wx.getStorageSync('awbopenid')){
                    openId=wx.getStorageSync('awbopenid')
                }else {
                    // 如果始终没有信息，则弹出绑定手机信息
                    this.setData({
                        showBindPhoneDialog: true,
                    })
                    return
                }

            }
            console.log('onLoad')
            this.setData({
                scene: decodeURIComponent(query.scene),
                page: query.page,
                url: query.url,
                openId : openId
            })

            // this.doLogin();
            this.listSelfhandDevice();
            this.getInProcessBill();
            this.listFinishedBillByOpenId()
        },
        /**
         * 选择衡器
         * @param event
         */
        selectPound:function (event) {
            let item = event.currentTarget.dataset.item;
            this.setData({
                showDialog: false,
                'billVo.selfhandIp':item.clientIP,
                currentWeight:'',
                'billVo.deviceName':item.deviceName
            })
            // 立刻读数。
            this.getCurrentWeightByIp();
        },




        hideModal:function () {
            this.setData({
                showPoundBillDialog: false,
            })
        },
        // 展示磅单
        showDetail:function (event) {
            let item = event.currentTarget.dataset.item;
            this.setData({
                showPoundBillDialog: true,
                item:item,
            })
        },
        showSelectPoundModal:function () {
            this.setData({
                showDialog: true
            })
        },
        hideSelectPondModal:function () {
            this.setData({
                showDialog: false
            })
        },
        /**
         * 确认磅
         */
        async confirmPound () {
            var that = this;
            if (!that.data.billVo){
                wx.showToast({
                    title: '没有可过磅单据',
                    icon: 'none'
                });
                return;
            }
            if (that.data.billVo.selfhandIp==''){
                that.setData({
                    showDialog: true
                })
                return;
            }
            if (that.data.currentWeight==''||that.data.currentWeight<1){
                wx.showToast({
                    title: '保存失败，无效重量！',
                    icon: 'none'
                });
                return;
            }

            //   已处理成功
            const res = await app.awbApiInstance.post('/openApi/poundbill/confirmPound', {
                "selfhandIp":that.data.billVo.selfhandIp,
                "openId":that.data.openId,
                "cardId":that.data.billVo.driverCardId,
                "pkPoundbill":that.data.billVo.pkPoundbill
            })
        },
        captchaChange(e){
            this.setData({
                captcha: e.detail.value
            })
        },
        phoneNumberChange(e){
            console.log(e.detail.value)
            this.data.phoneNumber=e.detail.value
        },

        /**
         * 获取验证码
         */
        async getOpenIdByPhoneNumber() {
            console.log(this.data.phoneNumber)
            var that = this;
            if(!/^1[3-9]\d{9}$/.test(this.data.phoneNumber)){
                wx.showToast({
                    title: "请输入正确的手机号",
                    icon: 'none',
                    duration: 3000
                });
                return
            }
            if (this.data.captcha===''){
                wx.showToast({
                    title: "请输入验证码",
                    icon: 'none',
                    duration: 3000
                });
                return
            }
            // 获取可过磅 设备
            const res = await app.awbApiInstance.post('/openApi/wx/getOpenIdByPhoneNumber', {
                "phoneNumber":that.data.phoneNumber,
                "captcha":that.data.captcha
            },function () {
                // 处理失败的。

            })

            clearInterval(that.data.timer);
            that.data.timer = null;
            console.log(res)
            that.data.openId=res.data;
            wx.setStorageSync('awbopenid',that.data.openId)
            wx.setStorageSync('phoneNumber',that.data.phoneNumber)
            wx.showToast({
                title: "绑定成功",
                icon: 'none',
                duration: 2000
            });
            //隐藏 并关闭
            that.setData({
                countdown:60,
                showBindPhoneDialog:false,
                btnSendCaptchaText: '验证码'
            });

        },
        /**
         * 获取验证码
         */
        async sendCaptcha() {
            console.log(this.data.phoneNumber)
            var that = this;
            if(!/^1[3-9]\d{9}$/.test(this.data.phoneNumber)){
                wx.showToast({
                    title: "请输入正确的手机号",
                    icon: 'none',
                    duration: 3000
                });
                return
            }

            // 获取可过磅 设备
            const res = await app.awbApiInstance.post('/openApi/wx/sendCaptcha', {
                "phoneNumber":that.data.phoneNumber
            },function () {
                // 处理失败的。

            })
            this.startCountdown();
        },
        // 定时器 发送验证吗
        startCountdown: function() {
            // 使用闭包来保持对页面的引用
            const that = this;
            // 设置一个定时器，每秒更新一次倒计时
            this.data.timer = setInterval(function() {
                // 减少倒计时时间
                let countdown = that.data.countdown - 1;
                // 更新页面数据
                that.setData({
                    countdown: countdown,
                    btnSendCaptchaText: countdown+'秒后再发'
                });
                console.log(that.data.countdown)
                // 当倒计时到达0时，清除定时器
                if (countdown <= 0) {
                    clearInterval(that.data.timer);
                    that.data.timer = null;
                    that.setData({
                        countdown:60,
                        btnSendCaptchaText: '验证码'
                    });

                }
            }, 1000); // 每秒更新一次（1000毫秒）
        },
        /**
         * 根据openId.查询可以过磅的单据
         */
        async listFinishedBillByOpenId() {
            console.log(this.data)
            var that = this;
            // 获取可过磅 设备
            const res = await app.awbApiInstance.post('/openApi/poundbill/listFinishedBillByOpenId', {
                "openId":that.data.openId
            },function () {
                // 处理失败的。

            })
            that.setData({
                poundbillList: res.rows
            })
        },


        /**
         * 根据openId.查询可以过磅的单据
         */
        async listSelfhandDevice() {
            console.log(this.data)
            var that = this;
            // 获取可过磅 设备
            const res = await app.awbApiInstance.post('/openApi/poundbill/listSelfhandDevice', {
                "openId":that.data.openId
            },function () {
                // 处理失败的。

            })
            that.setData({
                selfhandleDeviceList: res.rows
            })
        },

        /**
         * 根据openId.查询可以过磅的单据
         */
        async getInProcessBill () {
            console.log(this.data)
            var that = this;

            // 获取可过磅信息接口  已处理成功
            const res = await app.awbApiInstance.post('/openApi/poundbill/getInProcessBill', {
                "openId":that.data.openId
            },function () {
                // 处理失败的。
                that.setData({
                    billVo: null
                })
            })
            that.setData({
                billVo: res.data
            })
            if (that.data.billVo&&that.data.billVo.selfhandIp==''){
                //选择磅头。
                that.setData({
                    showDialog: true
                })
            }
        },


        /**
         * 暂时不用， 只通过消息模板进入记录openId
         * @returns {Promise.<void>}
         */
        async doLogin() {
            try {
                var that =this;
                wx.login({
                    success: function (res) {
                        console.log('res',res.code);
                        if(res.code){
                            const result = app.awbApiInstance.postWithBackground('/openApi/wx/getOpenIdByCode', {
                                "code":res.code
                            },function () {
                                console.log('查询异常')
                            })
                            console.log(result)
                        }
                    }
                })
            } catch (e) {
                console.log(e);
            }
        },
        /**
         * Z只有设置了自助机IP　才会获取
         * @returns {Promise.<void>}
         */
        async getCurrentWeightByIp() {
            let that=this
            console.log(that.data)
            if (!that.data.billVo){
                wx.showToast({
                    title: '没有可过磅单据',
                    icon: 'none'
                });
                return
            }
            if (!that.data.showDialog&&(that.data.billVo.selfhandIp=='')){
                //选择磅头。
                that.setData({
                    showDialog: true
                })
            }
            // 获取可过磅信息接口  已处理成功
            const res =await app.awbApiInstance.postWithBackground('/openApi/poundbill/getCurrentWeightByIp', {
                "selfhandIp":that.data.billVo.selfhandIp
            },function () {
                console.log('输出异常')
                that.setData({
                    currentWeight: ''
                })
            })
            console.log('设置磅重')
            that.setData({
                currentWeight: res.data
            })
        },
        gotoVisitor() {
            wx.navigateTo({
                url: '/pages/visitorLogin/visitorLogin',
            })
        },
    }

})